package com.example.remotelybootpc;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity {

    private Button btn_boot;
    private Button btn_conn;
    private TextView text_result;
    private TextView text_result2;
    private MqttClient client;
    MqttConnectOptions options = null;
    private ScheduledExecutorService scheduler;
    private Handler handler;
    private String host = "tcp://10.75.80.100:1883";
    private String username = "lier222";
    private String password = "1234qwer";
    private String mqtt_id = "mqttx_1234";
    private String mqtt_sub_topic = "android";
    private String mqtt_pub_topic = "esp8266";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*==========================================================================*/
        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        /*==========================================================================*/
        btn_boot = findViewById(R.id.btn_boot);
        btn_conn = findViewById(R.id.btn_conn);
        text_result = findViewById(R.id.text_result);
        text_result2 = findViewById(R.id.text_result2);

        Mqtt_init();
        startReconnect();
        handler = new Handler(Looper.myLooper()){
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1: //开机校验更新回传
                        break;
                    case 2: //反馈回转
                        break;
                    case 3:
                        Log.i("MQTT数据",msg.obj.toString());
                        break;
                    case 30:
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 31:
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        try{
                            client.subscribe(mqtt_sub_topic,1);
                        }catch (MqttException e){
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;

                }
            }
        };
        btn_conn.setOnClickListener(view -> {

        });
        btn_boot.setOnClickListener(view -> {
            publishmessageplus(mqtt_sub_topic,"启动！！！");
        });
    }

    /* 与远程地址建立连接*/
    private boolean connect(String ip, int port) {

        return false;
    }

    /*发送命令*/
    private void sent(String msg){

    }

    /*接收远程地址回复信息*/
    private String receive(){

        return null;
    }

    private void Mqtt_init(){
        try {
            client = new MqttClient(host, mqtt_id,new MemoryPersistence());
            MqttConnectOptions option = new MqttConnectOptions();
            option.setCleanSession(false);
            option.setUserName(username);
            option.setPassword(password.toCharArray());
            option.setConnectionTimeout(10);
            option.setKeepAliveInterval(20);
            options = option;
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    Log.i("connectionLost", "连接丢失");
                    startReconnect();
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    Log.i("messageArrived","messageArrived------------");
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = mqttMessage.toString();
                    handler.sendMessage(msg);
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    Log.i("deliveryComplete","deliveryComplete------------");
                }
            });
        } catch (MqttException e) {
            Log.i("error","出错了");
            e.printStackTrace();
        }
    }

    private void Mqtt_connect(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected())){
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect(){
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if(!client.isConnected()){
                    Mqtt_connect();
                }
            }
        },0*1000, 10*1000, TimeUnit.MILLISECONDS);
    }

    private void publishmessageplus(String topic, String msg){
        if(client == null || !client.isConnected())
            return;
        MqttMessage message = new MqttMessage();
        message.setPayload(msg.getBytes());
        try {
            client.publish(topic, message);
        }catch (MqttException e) {
            e.printStackTrace();
        }

    }
}